import React, { useCallback, useState } from 'react';
import { useAsyncState, asCallApi, useApi, usePromise, callApi } from 'clib/hooks/async';
import { number, string } from 'mobx-state-tree/dist/internal';
import { login, logout, useLoginState } from 'clib/session';

// 封装登录逻辑，包括登录，会话刷新token，退出登录
// 可配置触发函数，送入用户名密码
// 可配置 appCode
// 可配置 appSecret
// 可配置登录成功失败回调
// 内部自动保存 token 到 localStorage，命名加系统名称
// portal const AppSecret = 'HUkntIPV'
// oss    const APP_SECRET = 'hyFm(K7&';

interface ILoginResp {
  accessToken: string;
  expiresIn: number;
  redirectUrl: null | string;
  refreshToken: string;
  scope: null;
  tokenType: "access_token";
  urlToken: string;
  username: string;
}

function useLogin() {
  const appCode: string = 'oss';
  const appSecret: string = 'hyFm(K7&';


  const [username, setUsername] = useState(() => {
    // const saved = localStorage.getItem('enncloud-username');
    // if (saved) return saved;
    return '';
  });
  function doLogin(username: string, password: string) {
    callApi(`!post /ucenter/api/auth/token`, {
      username,
      password,
      appSecret,
    }).then(resp => {
      if (!resp.errorCode) { // 成功登录
        const content: ILoginResp = resp.content;
        localStorage.setItem('enncloud-accessToken', content.accessToken);
        localStorage.setItem('enncloud-refreshToken', content.refreshToken);
        localStorage.setItem('enncloud-urlToken', content.urlToken);
        localStorage.setItem('enncloud-username', content.username);
        setUsername(content.username);
      } else { // 失败登录

      }
      console.dir(resp);
    });
  }
  return { doLogin, username };
}

const PORT = window.location.port;

export default function Login() {
  console.log('window.opener', window.opener === window, window.opener && window.opener.postMessage);
  // console.log('window.opener', window.opener && window.opener.localStorage.getItem('enncloude-accessToken'));


  // 全自动集成 API，自动触发，结果自动回写
  const asAuth = useApi([false],
    () => ['post /ucenter/api/auth/token', {
      username: 'oss_view',
      password: '123456',
      appSecret: 'hyFm(K7&',
    }], {
    ForceReExecuteDelay: 1000,
    LoadingDelay: 200,
  });

  // const { doLogin, username } = useLogin();
  const username = useLoginState();

  const asNeedAuth = useApi([false],
    () => ['get /oss/v1.0/capacity/hostResourceList', {
      resourceType: '青云',
      queryValue: '2020-11-25',
    }]);

  const tsPanelList = useApi([username], () => [
    'get /oss/v1.0/nc/ncInfos', {
      orgCode: 100001,
    }]);

  const direct = useCallback(() => {
    callApi('get /oss/v1.0/nc/ncInfos', {
      orgCode: 100001,
    }).then(console.dir);
  }, []);


  return (
    <div>
      <div>
        <span>{username}</span>
        <button onClick={() => login('dulaoban', '123456')}>登录</button>
        <button onClick={logout}>退出</button>
        <button onClick={direct}>调后台接口</button>
        <a target="_self" href={window.location.href.replace(PORT, '5001')}>窗口内跳转</a>
        <a target="_blank" href={window.location.href}>跳转新窗口</a>
        <button onClick={() => { document.title = String(Date.now()) }}>改title</button>
      </div>
      <pre>{JSON.stringify(tsPanelList, null, 2)}</pre>
    </div>
  );
}
